﻿#region Copyright & licence

// This file is part of Refix.
// 
// Refix is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
// 
// Refix is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with Refix.  If not, see <http://www.gnu.org/licenses/>.
// 
// Copyright (C) 2010-11 David Musgrove and others.

#endregion

using System;
using System.IO;
using System.Linq;

using Refix.Core.IO;
using Refix.Core.Options;
using Refix.Core.Properties;
using Refix.Core.Repository;

namespace Refix.Core.Commands
{
    public class Postbuild : SingleSolutionCommand
    {
        public string Configuration { get; set; }

        protected override string HelpText
        {
            get { return ResourceDispenser.GetString("POSTBUILD_HELP"); }
        }

        public override bool Validate()
        {
            if (Options.Options.Any(o => o is Verbose)
                && Options.Options.Any(o => o is Quiet))
            {
                OutputWriter.WriteLine(OutputVerbosity.Quiet, ResourceDispenser.GetString("OPTION_INVALID_COMBINATION"));
                ShowHelp();
                return false;
            }
            if (Options.Arguments.Count > 2 || Options.Arguments.Count == 0)
            {
                OutputWriter.WriteLine(OutputVerbosity.Quiet,
                                   ResourceDispenser.GetString("WRONG_NUMBER_OF_ARGUMENTS"));
                return false;
            }
            int index = 0;
            if (Options.Arguments.Count == 2)
            {
                FileName = Options.Arguments[index++];
                FileInfo[] fileInfos =
                    new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles(FileName);
                if (fileInfos.Length != 1)
                {
                    OutputWriter.WriteLine(OutputVerbosity.Quiet,
                                       ResourceDispenser.GetString("SINGLE_SOLUTION_FILE_DOESNT_EXIST"));
                    return false;
                }
                FileName = fileInfos[0].FullName;
            }
            else
            {
                FileInfo[] fileInfos =
                    new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles("*" + FileExtensions.Solution);
                if (fileInfos.Length == 0)
                {
                    OutputWriter.WriteLine(OutputVerbosity.Quiet,
                                       ResourceDispenser.GetString("SINGLE_SOLUTION_NO_SOLUTION_FILES"));
                    return false;
                }
                if (fileInfos.Length > 1)
                {
                    OutputWriter.WriteLine(OutputVerbosity.Quiet,
                                       ResourceDispenser.GetString("SINGLE_SOLUTION_MULTIPLE_SOLUTION_FILES"));
                    return false;
                }
                FileName = fileInfos[0].FullName;
            }
            Configuration = Options.Arguments[index];
            return true;
        }

        public override bool Execute()
        {
            var solutionFile = new SolutionFile(FileName);
            if (solutionFile.CachedProjectFiles.Values.Any(projectFile => !(projectFile.CheckDependencyFileExists())))
            {
                return false;
            }
            string refixFolderPath = Path.Combine(Path.GetDirectoryName(solutionFile.FileName), ".refix");
            foreach (ProjectFile projectFile in solutionFile.CachedProjectFiles.Values)
            {
                ProjectFile dependencyFile = projectFile.GetDependencyFile();
                string outputFolder = projectFile.GetBuildOutputFolder(Configuration);
                if (string.IsNullOrEmpty(outputFolder))
                {
                    if (projectFile.ProjectGuid != ProjectGuids.PrebuildProject
                        && projectFile.ProjectGuid != ProjectGuids.PostbuildProject)
                    {
                        OutputWriter.WriteLine(OutputVerbosity.Verbose,
                                               ResourceDispenser.GetString("POSTBUILD_PROJECT_CONFIGURATION_NOT_FOUND"),
                                               Path.GetFileNameWithoutExtension(projectFile.FileName), Configuration);
                    }
                    continue;
                }
                outputFolder = Path.Combine(Path.GetDirectoryName(projectFile.FileName), outputFolder);
                foreach (Reference assemblyBindingRedirect in dependencyFile.GetAllAssemblyBindingRedirects(projectFile))
                {
                    CopyFile(refixFolderPath, outputFolder, assemblyBindingRedirect, ".dll");
                    CopyFile(refixFolderPath, outputFolder, assemblyBindingRedirect, ".pdb");
                }
            }
            return new Clean { FileName = FileName, Options = Options }.Execute();
        }

        static private void CopyFile(string refixFolderPath, string outputFolder, Reference assemblyBindingRedirect,
                                     string extension)
        {
            string sourceFile = Path.Combine(refixFolderPath, assemblyBindingRedirect.AssemblyName + extension);
            string destinationFile = Path.Combine(outputFolder, assemblyBindingRedirect.AssemblyName + extension);
            if (File.Exists(sourceFile) && !File.Exists(destinationFile))
            {
                File.Copy(sourceFile, destinationFile);
            }
        }
    }
}